# -*- coding: UTF-8 -*-  

import itchat
import datetime
from sqlalchemy import or_
from hashids import Hashids
import hashlib
from donato.database import Session, Message, GroupMember, Contacter, Droid, GroupMentionLog, Command
from donato import logger, app
import os

itchat.load_login_status(fileDir='itchat.pkl')

session = Session()

hashids = Hashids(salt='star wars', min_length=5)

def grouplog_save(nickname, group, content, ctime, groupmember, command=None):
	"""Save bot isAt message and do reply as templated if command captured
	Args:
		msg(dict): message captured
	"""
	new_groupMentionLog = GroupMentionLog(group_member_name = groupmember.nick_name,
											group_name = group.nick_name,
											message_content = content,
											message_time = datetime.datetime.fromtimestamp(ctime).strftime('%Y-%m-%d %H:%M:%S'),
											group = group,
											groupmember = groupmember,
											command = command)

	session.add(new_groupMentionLog)
	session.commit()

def msg_save(username, nickname, isat, msgid, user, ctime, content_transformer, type_transformer,command=None):
	"""Save all group messages in database.message
	Args:
		msg(dict): message captured
		content_transformer(str): processed type of message
		type_transformer(str): processed content str on message
	"""
	this_droid = session.query(Droid).filter(Droid.nick_name==user['Self']['NickName']).first()
	sender = session.query(Contacter).filter(Contacter.nick_name==user['NickName']).filter(Contacter.droid_id == this_droid.id).first() 
	if not sender:
		sender = group_create(user['UserName'], this_droid)
	
	receiver = session.query(Contacter).filter(Contacter.nick_name==user['Self']['NickName']).filter(Contacter.droid_id == this_droid.id).first()
	if not receiver:
		print "Please keep the bot itself as contacter in contacter table!!!"

	groupmember = session.query(GroupMember).filter(or_(GroupMember.nick_name==nickname, GroupMember.display_name==nickname)).filter(GroupMember.group_id == sender.id).filter(Contacter.droid_id == this_droid.id).first()
	if not groupmember:
		groupmember = groupmember_create(username, sender, this_droid)

	# if not sender:
	# 	load_groups_by_username(user['UserName'])
	# 	sender = session.query(Contacter).filter(Contacter.username==user['UserName']).filter(Contacter.droid == this_droid).first()

	new_msg = Message(content = content_transformer,
					message_type = type_transformer,
					message_time = datetime.datetime.fromtimestamp(ctime).strftime('%Y-%m-%d %H:%M:%S'),
					msg_id = msgid,
					group_member_name = nickname,
					sender_name = sender.nick_name,
					receiver_name = receiver.nick_name,
					sender = sender,
					receiver = receiver,
					groupmember = groupmember,
					droid = this_droid)

	session.add(new_msg)
	session.commit()

	if (isat):
		grouplog_save(nickname, sender, content_transformer, ctime, groupmember, command=command)

def group_create(username, droid):
	group = itchat.update_chatroom(username, detailedMember=False)
	new_group = Contacter(nick_name = group['NickName'],
								  contacter_type = 'GROUP',
								  last_update_time = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S'),
								  head_img_url = get_avatar(chatroomUserName = group['UserName']),
								  alias = group['Alias'],
								  city = group['City'],
								  province = group['Province'],
								  display_name = group['DisplayName'],
								  remark_name = group['RemarkName'],
								  contact_flag = group['ContactFlag'],
								  member_count = group['MemberCount'],
								  sex = group['Sex'],
								  username = group['UserName'],
								  droid = droid)
	session.add(new_group)
	session.commit()
	new_group.hashcode = hashids.encode(new_group.id)
	session.flush()

	return new_group

def groupmember_create(member_username, group, droid):
	for member in itchat.update_chatroom(group.username, detailedMember=True)['MemberList']:
		if member['UserName'] == member_username:
			new_group_member = GroupMember(nick_name = member['NickName'], 
											   city = member['City'],
											   alias = member['Alias'],
											   last_update_time = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S'),
											   head_img_url = get_avatar(userName=member['UserName'],chatroomUserName=group.username),
											   contact_flag= member['ContactFlag'],
											   display_name = member['DisplayName'],
											   member_count = member['MemberCount'],
											   province = member['Province'],
											   remark_name = member['RemarkName'],
											   sex = member['Sex'],
											   signature = member['Signature'],
											   username = member['UserName'],
											   droid = droid,
											   group = group)
			session.add(new_group_member)
			session.commit()
			return new_group_member
	logger.info('insert new group member failed - no such username')

def get_avatar(userName=None, chatroomUserName=None):
	"""Generate path of avatar files of all contactors and groupmember
	Args:
		userName(str): Friend od GroupMember username
		chatroomUserName(str): Group username
	Returns:
		String of avatar picture file path
	"""
	nameStr = userName if chatroomUserName is None else (userName+chatroomUserName) if userName is not None else chatroomUserName
	avatarName = hashlib.sha224(nameStr).hexdigest()
	save_path = app.config['UPLOAD_PATH'] + 'avatar/' + datetime.datetime.today().strftime('%Y%m%d') + '/'
	if not os.path.exists(save_path):
		os.makedirs(save_path)

	file_path = save_path + avatarName + '.png'

	itchat.get_head_img(userName = userName, chatroomUserName = chatroomUserName, picDir = file_path)

	return file_path


